package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * 把请求信息封装为Request对象（根据InputSteam输⼊流封装）
 */
public class Request {

    private String method;           // 请求⽅式，比如GET/POST
    private String url;              // 例如 /,/index.html
    private String host;             // 例如 localhost
    private String port;             // 例如 8080
    private InputStream inputStream; // 输⼊流，其他属性从输入流中解析出来

    public Request() {
    }

    /**
     * 构造器，输⼊流传⼊
     * @param inputStream
     * @throws IOException
     */
    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;
        // 从输⼊流中获取请求信息
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);
        String inputStr = new String(bytes);
        String[] lines = inputStr.split("\\n");
        for (String line : lines) {
            String[] columns = line.replaceAll("\r", "").split(" ");
            if ("GET".equals(columns[0]) || "POST".equals(columns[0])) {
                // GET / HTTP/1.1
                this.method = columns[0].trim();
                this.url = columns[1].trim();
                System.out.println("=====>>method:" + method);
                System.out.println("=====>>url:" + url);
            }
            if ("Host:".equals(columns[0])) {
                String[] hosts = columns[1].split(":");
                this.host = hosts[0].trim();
                this.port = hosts[1].trim();
                System.out.println("=====>>host:" + host);
                System.out.println("=====>>port:" + port);
            }
        }
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getHost() {
        return host;
    }

    public String getPort() {
        return port;
    }

}
